from random import randint

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from .serializers import RegisterSMSCodeSerializer
from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP


class RegisterSMSCodeView(GenericAPIView):
    """
    获取短信验证码
    GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx&image_code_id=xxxx
    """
    serializer_class = RegisterSMSCodeSerializer
    def get(self, request,mobile):
        # 使用序列化器验证text,image_code_id
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 链接数据库
        redis_conn = get_redis_connection('code')
        # 判断用户是否频繁获取
        if redis_conn.get('sms_flag_%s' % mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        # 生成短信验证码
        sms_code = '%06d'%randint(0,999999)
        # redis增加记录
        redis_conn.setex('sms_%s' % mobile, 5*60,sms_code)
        redis_conn.setex('sms_flag_%s' % mobile, 60,1)

        # 发送短信
        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,5],1)
        #　返回响应
        from celery_tasks.sms.tasks import send_sms_code

        send_sms_code.delay(mobile,sms_code)
        return Response({'message':'ok'})





class RegisterImageCodeView(APIView):
    """生成图片验证码
    GET verifications/imagecodes/(?P<image_code_id>.+)/
    需要通过jS生成一个唯一码，以确保后台对图片进行校验
    """
    def get(self,request,image_code_id):
        """通过第三方库生成图片和验证码captcha"""
        # 1 创建图片和验证码
        text, image = captcha.generate_captcha()
        # 2 通过redis保存验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex("img_%s" % image_code_id, 60,text)

        # 3 返回图片
        return HttpResponse(image,content_type='image/jpeg')